﻿/// <reference path="jquery-vsdoc-1.7.2.js" />
/// <reference path="google.maps-v3-vsdoc.js" />
var app = {
	renderers : {},
	services : {},
	resources : {},
	methods : {}
};
$(document).ready(function (e) {
	// Autocomplete Initialisation
	var destinationInput = document.getElementById("destination");
	autocompleter = new google.maps.places.Autocomplete(destinationInput);
	// Resources
	app.resources.marker = new google.maps.MarkerImage('img/sign.png');
	// Map Initialisation
	app.services.geocoder = new google.maps.Geocoder();
	app.services.directions = new google.maps.DirectionsService();
	app.renderers.directions = new google.maps.DirectionsRenderer();
	app.renderers.map = new google.maps.Map(
							document.getElementById("map_canvas"),
							{
								zoom: 16,
								minZoom: 12,
								maxZoom: 20,
								center: new google.maps.LatLng(57.050068, 9.917908),
								mapTypeId: google.maps.MapTypeId.ROADMAP
							});
	app.renderers.directions.setMap(app.renderers.map);
	// Methods
	app.methods.Route = function (origin, destination) {
		var request = {
			origin: origin,
			destination: destination,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		app.services.directions.route(request, function (result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				app.renderers.directions.setDirections(result);
			}
		});
	};
	//geolocalization
	app.methods.getLocation = function () {
		if (navigator.geolocation) {
			var timeoutVal = 10 * 1000 * 1000;
			navigator.geolocation.getCurrentPosition(
				displayPosition,
				displayError,
				{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
		  	);
		}
		else {
			alert("Geolocation is not supported by this browser");
		}

		function displayPosition(position) {
			console.log(position);
			var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			app.resources.currentLatLng = pos;
			var markerImage = new google.maps.MarkerImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
			var marker = new google.maps.Marker(
			{
				position: pos,
				map: app.renderers.map,
				icon: markerImage
			});
			app.renderers.map.setCenter(pos);
			/*
			* Get the address coresponding to the current location
			*/
			app.services.geocoder.geocode({ latLng: pos }, function (results, status) {
				if ((status == google.maps.GeocoderStatus.OK) && (results.length > 0)) {
					var elem = results[0];
					$("#currentLocation")
                        .val(elem.formatted_address)
                        .attr("title", elem.formatted_address);
				}
			});
		}
		function displayError(error) {
			var errors = {
				1: 'Permission denied',
				2: 'Position unavailable',
				3: 'Request timeout'
			};
			alert("Error: " + errors[error.code]);
		}
	}
	// Event Listeners
	$(destinationInput).change(function () {
		var origin = app.resources.currentLatLng;
		var destination = $(this).val();
		app.methods.Route(origin, destination);
	});

	function saveCoord(latitude, longitude) {
		$.ajax({
			type: 'POST',
			url: 'Default.aspx/saveMarker',
			contentType: 'application/json; charset=utf-8',
			data: '{ "latitude":' + latitude + ', "longitude":' + longitude + '}',
			dataType: 'json',
			success: function () { },
			error: function () { alert("failure"); }
		});
	}

	function loadCoord() {
		$.ajax({
			type: "POST",
			url: "Default.aspx/loadMarkers",
			data: "{}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function (response) {
				var coords = response.d;
				$.each(coords, function (index, coord) {
					createInputMarker(new google.maps.LatLng(coord.Latitude, coord.Longitude));
				});
			},
			failure: function () {
				alert("failure");
			}
		});
	}

	function createInputMarker(point) {
		var marker = new google.maps.Marker({ position: point, map: app.renderers.map });
		return marker;
	}
	// == Listen for map click and add an input marker
	google.maps.event.addListener(app.renderers.map, "click", function (event) {
		createInputMarker(event.latLng);
		saveCoord(event.latLng.lat(), event.latLng.lng());
	});

	app.methods.getLocation();
	loadCoord();
});